package com.bit.bit_forum.interceptor;

import com.bit.bit_forum.config.AppConfig;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
/**
 * 登录拦截器
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Value("${forum.login.url}")
    private String defaultUrl;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获取session对象
        HttpSession session = request.getSession(false);
        if(session!=null && session.getAttribute(AppConfig.USER_SESSION)!=null ){
            //验证通过,用户已登录
            return true;
        }
        //验证不通过,跳转到登录界面
        //先进行url合法校验:
        if(!defaultUrl.startsWith("/")){
            defaultUrl = "/"+defaultUrl;
        }
            response.sendRedirect(defaultUrl);
//        response.sendRedirect("/login-in.html");
        //中断流程
        return false;
    }


}
